// pages/home/home.js
const homeService = require('../../services/home/home.js');
const config = require('../../utils/config');
const globalModel = require('../../model/global');
const userModel = require('../../model/user');

Page({
  data: {
    wines: [], // 存储酒品数据
    activities: [], // 存储活动数据
    isMember: false,
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
            active: 0
        })
    }
  },
  
  onLoad() {
    // 页面加载时请求推荐酒品和活动数据
    this.fetchHomeSuggest();
    const userData = userModel.getUserData();

    // 判断用户角色是否为VIP会员
    if (userData.info.role !== 'GUEST') {
      this.setData({ isMember: true });
    }
  },

  onShareAppMessage() {
    return {
      title: "美酒城市",
      path: "/pages/home/home",
    }
  },
  
  // 请求推荐酒品数据
  fetchHomeSuggest() {
    homeService.fetchHomeSuggest()
      .then((data) => {
        const { servicePhone } = data;

        // 存储全球变量 servicePhone
        if (servicePhone) {
          globalModel.setServicePhone(servicePhone);
        }

        // 将图片 URL 加上 backendUrl 前缀
        const wines = data.wines.map(wine => ({
          ...wine,
          imageUrl: `${config.backendUrl}${wine.imageUrl.startsWith('/') ? wine.imageUrl : "/"+wine.imageUrl}`,
        }));

        const activities = data.activities.map(activity => ({
          ...activity,
          imageUrl: `${config.backendUrl}${activity.imageUrl.startsWith('/') ? activity.imageUrl : "/" + activity.imageUrl}`,
        }));

        this.setData({
          wines: wines || [],
          activities: activities || [],
        });
      })
      .catch((err) => {
        wx.showToast({
          title: err,
          icon: 'none',
        });
      });
  },

  // 跳转到酒品详情页
  navigateToDetail(event) {
    const wineId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/goods/details/index?id=${wineId}`,
    });
  },
});
